using System;
using System.Collections.Generic;
using System.Linq;
namespace WebClient.Controllers
{
	#region using
	using System.Web.Mvc;
	using WebClient.Models.ViewModels;
	using WebClient.Models;
	using WebClient.Models.Repositories;
	using WebClient.Helpers;
	using System.Web.Security;
    using WebClient.CF_DAL_WS;
    using System.Drawing;
	#endregion
	public partial class AdminController: BaseController
	{
		public ActionResult SelectFood()
		{
			var data = new DataTransferViewModel
			{
				EnumViewModelType = EnumViewModel.ADMIN_FOOD
			};
			return View(CreateViewModel(data));
		}


		public ActionResult SelectFoodByIDMenu(int idmenu, int idrestaurant)
		{
			var data = new DataTransferViewModel
			{
                IDRestaurant = idrestaurant,
				IDMenu = idmenu,
				EnumViewModelType = EnumViewModel.ADMIN_FOOD,
			};
			return View("SelectFood", CreateViewModel(data));
		}

		public ActionResult SelectFoodByIDMenuPaging(int idmenu)
		{
			var data = new DataTransferViewModel
			{
				IDMenu = idmenu,
				EnumViewModelType = EnumViewModel.ADMIN_FOOD,
			};
			return PartialView("Templates/TH_ListFood", CreateViewModel(data));
		}


		[AcceptVerbs(HttpVerbs.Delete)]
		public JsonResult DeleteFood(int id)
		{
			var deleteItem = _repFood.SelectByID(id);
            var filename = deleteItem.Image;
            var idmenu = deleteItem.IDMenu;
            var result = _repFoodDetail.Delete(id);
            if (result)
            {
                result = _repFood.Delete(id);
                if (result)
                {
                    DALService.Instance.DeleteFile(filename);
                }
            }
			return Json(new{
				Success = result,
				RecordCount = _repFood.SelectAll().Count,
				DeleteId = id
			});
		}

		public ActionResult DetailOfFood(int id, int idrestaurant)
		{
			var data = new DataTransferViewModel
			{
				EnumViewModelType = EnumViewModel.ADMIN_DETAILOF_FOOD,
                IDFood = id,
                IDRestaurant = idrestaurant
			};
			return View(CreateViewModel(data));
		}

		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult UpdateFood(FormCollection forms)
		{
			string id = forms.GetValues("Food_ID")[0];
            string idrestaurant = forms.GetValues("Food_IDRestaurant")[0];
			string idmenu = forms.GetValues("Food_IDMenu")[0];
			string name = forms.GetValues("Food_Name")[0];
			string price = forms.GetValues("Food_Price")[0];
            string introduction = forms.GetValues("Food_Introduction")[0];
            string sortintroduction = forms.GetValues("Food_SortIntroduction")[0];
			var file = Request.Files["Food_Image"];

			var editItem = _repFood.SelectByID(int.Parse(id));
			editItem.IDMenu = int.Parse(idmenu.Replace(".", "").Replace(",", ""));
			editItem.Name = name;
            editItem.SortIntroduction = sortintroduction;
            if (price != "")
            {
                editItem.Price = float.Parse(price);
            }

			var result = false;
			if (file.ContentLength != 0)
			{
                byte[] image = null;
                string refName = string.Empty;
                // Read image to byte array
                result = UploadFile(file, id, ref image, ref refName);
                if (result)
                {
                    ImageEditing imgedit = new ImageEditing();
                    // Convert byte array to image
                    Image sourceImg = imgedit.ByteArrayToImage(image);
                    Image resultimage = null;
                    int widthToResize = WebConfiguration.UploadImageWidth;
                    int heightToResize = WebConfiguration.UploadImageHeight;

                    try
                    {
                        // Resize image
                        resultimage = imgedit.Resize(widthToResize, heightToResize, sourceImg);
                        if (resultimage != null)
                        {
                            image = imgedit.ImageToByteArray(resultimage); 
                            // Upload resize image to server
                            DALService.Instance.UploadFile(refName, image, editItem.Image);
                            editItem.Image = refName;
                            editItem.ContentType = file.ContentType;
                        }
                    }
                    catch (Exception ex)
                    {
                        GlobalVariables.Logger.Error(string.Format("Error on UploadFile: {0}", ex.ToString()));
                    }
                }
			}
            result = _repFood.Update(editItem);
            // Continue update detail
            if (result)
            {
                var detail = _repFoodDetail.SelectByID(int.Parse(id));
                detail.Introduction = introduction;
                result = _repFoodDetail.Update(detail);
            }
			var data = new DataTransferViewModel
			{
				EnumViewModelType = EnumViewModel.ADMIN_DETAILOF_FOOD,
				IDFood = int.Parse(id.Replace(".", "").Replace(",", "")),
                IDRestaurant = int.Parse(idrestaurant),
				InfoText = result ? "Item has been updated" : "Cannot update this item"
			};
			return View("DetailOfFood", CreateViewModel(data));
		}


		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult InsertFood(FormCollection forms)
		{
            string idrestaurant = forms.GetValues("Food_IDRestaurant")[0];
			string idmenu = forms.GetValues("Food_IDMenu")[0];
			string name = forms.GetValues("Food_Name")[0];
			string price = forms.GetValues("Food_Price")[0];
            string introduction = forms.GetValues("Food_Introduction")[0];
            string sortintroduction = forms.GetValues("Food_SortIntroduction")[0];
			var file = Request.Files["Food_Image"];
			var newItem = new FoodDTO
			{
				IDMenu = int.Parse(idmenu),
				Name = name,
                SortIntroduction = sortintroduction,
                Image = "noimages.png",
                ContentType = "image/x-png"
			};
            if (price != "")
            {
                newItem.Price = float.Parse(price);
            }
			var result = _repFood.Insert(ref newItem);
			if (result)
			{
                if (file.ContentLength != 0)
                {
                    byte[] image = null;
                    string refName = string.Empty;
                    result = UploadFile(file, newItem.ID.ToString(), ref image, ref refName);
                    if (result)
                    {
                        ImageEditing imgedit = new ImageEditing();
                        // Convert byte array to image
                        Image sourceImg = imgedit.ByteArrayToImage(image);
                        Image resultimage = null;
                        int widthToResize = WebConfiguration.UploadImageWidth;
                        int heightToResize = WebConfiguration.UploadImageHeight;

                        try
                        {
                            // Resize image
                            resultimage = imgedit.Resize(widthToResize, heightToResize, sourceImg);
                            if (resultimage != null)
                            {
                                image = imgedit.ImageToByteArray(resultimage);
                                // Upload resize image to server
                                var addedItem = _repFood.SelectByID(newItem.ID);
                                if (addedItem != null)
                                {
                                    DALService.Instance.UploadFile(refName, image, string.Empty);
                                    addedItem.Image = refName;
                                    addedItem.ContentType = file.ContentType;
                                    result = _repFood.Update(addedItem);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            GlobalVariables.Logger.Error(string.Format("Error on UploadFile: {0}", ex.ToString()));
                        }
                    }
                }
                // Continue insert detail
                var detail = new FoodDetailDTO
                {
                    ID = newItem.ID,
                    Introduction = introduction
                };
                result = _repFoodDetail.Insert(detail);
			}
			var data = new DataTransferViewModel
			{
				IDMenu = int.Parse(idmenu),
				EnumViewModelType = EnumViewModel.ADMIN_FOOD,
                IDRestaurant = int.Parse(idrestaurant),
				InfoText = result ? "New item has been added" : "Cannot insert new item"
			};
			return View("SelectFood", CreateViewModel(data));
		}
	}
}
